<template>
  <div>
    <BasicTable @register="registerTable" @resize-column="handleResizeColumn">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" @click="handleGenerateDefaultView"> 新增默认 </a-button>
        <Popconfirm
          placement="top"
          title="是否确认删除"
          ok-text="确定"
          cancel-text="取消"
          @confirm="handleDelBatch"
        >
          <a-button type="primary"> 删除 </a-button>
        </Popconfirm>
      </template>

      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'clarity:note-edit-line',
              tooltip: '编辑',
              onClick: handleEdit.bind(null, record),
            },
            {
              icon: 'clarity:media-changer-outline-alerted',
              tooltip: '设计',
              onClick: handleDesign.bind(null, record),
            },
            {
              icon: 'clarity:file-group-line',
              tooltip: '显示规则',
              onClick: handleParams.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'topRight',
                confirm: handleDelete.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <FormViewModal @register="registerModal" @success="handleSuccess" />
    <DisplayRulesDrawer
      @register="registerDisplayRulesDrawer"
      @success="handleSuccessDisplayRulesDrawer"
    />
  </div>
</template>
<script lang="ts">
  import { defineComponent, h, computed, onMounted } from 'vue';
  import { Popconfirm } from 'ant-design-vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useDrawer } from '/@/components/Drawer';
  import FormViewModal from './FormViewModal.vue';
  import DisplayRulesDrawer from './displayRulesDrawer/DisplayRulesDrawer.vue';
  import { useModal } from '/@/components/Modal';
  import { columns, searchFormSchema } from './formView.data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useRouter } from 'vue-router';
  import { useI18n } from '/@/hooks/web/useI18n';
  const { t } = useI18n();
  import { useTabs } from '/@/hooks/web/useTabs';

  import {
    getFormViewList,
    getFormViewDel,
    getFormViewDelBatch,
    generateDefaultView,
  } from '/@/api/formDesign/formDesign';
  export default defineComponent({
    name: 'FormView',
    components: {
      BasicTable,
      FormViewModal,
      TableAction,
      DisplayRulesDrawer,
      Popconfirm,
    },
    setup() {
      const { resolve, currentRoute } = useRouter();
      const { setTitle } = useTabs();
      const formCode = computed(() => currentRoute.value?.query?.formCode);
      const [registerModal, { openModal }] = useModal();
      const { createMessage, createConfirm } = useMessage();
      const title = '视图';
      const [registerTable, { reload, getSelectRowKeys, setSelectedRowKeys, setProps }] = useTable({
        title,
        api: getFormViewList,
        columns,
        formConfig: {
          schemas: searchFormSchema,
        },
        searchInfo: {
          op: 'search',
        }, //额外的参数
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        showIndexColumn: true,
        indexColumnProps: { width: 50 },
        beforeFetch: (info) => {
          let newInfo = info;
          if (formCode.value) {
            newInfo.formCode = formCode.value;
          }
          return newInfo;
        },
        rowKey: 'id',
        rowSelection: {
          type: 'checkbox',
        },
        actionColumn: {
          width: 140,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          fixed: 'right',
        },
      });

      onMounted(() => {
        if (currentRoute.value?.query?.title) {
          const newTitle = `${title}-${currentRoute.value.query.title}`;
          setTitle(newTitle);
          setProps({ title: `${newTitle}` });
        }
      });

      function handleCreate() {
        openModal(true, {
          record: {
            formCode: formCode.value,
          },
          isUpdate: false,
        });
      }

      function handleGenerateDefaultView() {
        createConfirm({
          iconType: 'warning',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确认要新增默认视图么'),
          onOk: async () => {
            const params = {
              formCode: formCode.value,
            };
            await generateDefaultView(params);
            createMessage.success('操作成功');
            reload();
          },
        });
      }

      function handleEdit(record: Recordable) {
        openModal(true, {
          record,
          isUpdate: true,
        });
      }

      const handleDelete = async (record: Recordable) => {
        try {
          const params = {
            id: record.id,
          };
          await getFormViewDel(params);
          createMessage.success('操作成功');
          handleSuccess();
        } catch (err) {
          console.error(err);
        } finally {
        }
      };

      // const deleteAction = (ids) => {
      //   createConfirm({
      //     iconType: 'warning',
      //     title: () => h('span', t('common.prompt')),
      //     content: () => h('span', '您确定要删除么'),
      //     onOk: async () => {
      //       try {
      //         const params = {
      //           id: ids,
      //         };
      //         await getFormViewDel(params);
      //         createMessage.success('操作成功');
      //         handleSuccess();
      //       } catch (err) {
      //         console.error(err);
      //       } finally {
      //       }
      //     },
      //   });
      // };

      function handleSuccess() {
        setSelectedRowKeys([]);
        reload();
      }

      const handleDesign = (record) => {
        const { query } = currentRoute.value as any;
        let routeUrl: any = {};
        routeUrl = resolve({
          path: '/formViewDesign',
          query: {
            formCode: query?.formCode,
            id: record.id,
          },
        });
        const height = screen.height;
        const width = screen.width;
        window.open(
          routeUrl.href,
          '',
          `height=${height},width=${width},top=0, left=0,alwaysRaised=true,toolbar=no,location=no,resizable=no, scrollbars=yes ,`,
        );
      };

      const [registerDisplayRulesDrawer, { openDrawer }] = useDrawer();
      const handleSuccessDisplayRulesDrawer = () => {};
      //
      const handleParams = (record) => {
        openDrawer(true, {
          record,
          formCode: formCode.value,
        });
      };

      async function handleDelBatch() {
        let keys = getSelectRowKeys();
        if (keys.length == 0) {
          createMessage.warning('请选择需要删除的数据');
          return;
        }
        await getFormViewDelBatch({ ids: keys.join(',') }).then(() => {
          handleSuccess();
        });
      }

      return {
        registerTable,
        registerDisplayRulesDrawer,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        registerModal,
        handleParams,
        handleDesign,
        handleSuccessDisplayRulesDrawer,
        formCode,
        handleGenerateDefaultView,
        handleDelBatch,
      };
    },
  });
</script>
